import 'dart:async';
import 'package:chathouse/constant/my_color.dart';
import 'package:chathouse/widgets/form_widgets/form_widgets.dart';
import 'package:flutter/material.dart';
import 'package:chathouse/util/base_utils.dart';

class TimeButton extends StatefulWidget {
  Function callback;
  bool initStart;
  TimeButton(this.callback, {this.initStart = true, Key? key})
      : super(key: key);

  @override
  State<TimeButton> createState() => _TimeButtonState();
}

class _TimeButtonState extends State<TimeButton> {
  Timer? timer;
  String text = "重發驗證碼";
  bool enable = true;
  int count = 60 * 1000;

  @override
  void initState() {
    if (widget.initStart) {
      Future.delayed(const Duration(milliseconds: 50), () {
        startTimer();
      });
    }
    super.initState();
  }

  @override
  void dispose() {
    super.dispose();
    timer?.cancel();
  }

  @override
  Widget build(BuildContext context) {
    return FormWidgets.getTextButton(text, MyColors.brow_2551520,
            enable: enable)
        .setOnClickListener(() {
      if (enable) {
        startTimer();
        widget.callback();
      }
    });
  }

  void startTimer() {
    if (timer != null) {
      timer?.cancel();
      timer = null;
    }
    setState(() {
      enable = false;
    });
    timer = Timer.periodic(const Duration(milliseconds: 100), (val) {
      if (count <= 1) {
        setState(() {
          count = 60 * 1000;
          enable = true;
          text = "重發驗證碼";
          timer?.cancel();
        });
      } else {
        setState(() {
          count = count - 100;
          text = "重發驗證碼(${count ~/ 1000})";
        });
      }
    });
  }
}
